package application.view.viewComponent 
{
	import application.model.VO.GroupVO;
	import application.model.VO.PhotoAreaVO;
	import application.model.VO.PhotoVO;
	import ginger.events.DataEvent;
	import ginger.utils.ArrayUtil;
	import ginger.utils.ObjectPool;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import caurina.transitions.Tweener;
	import flash.utils.setTimeout;
	/**
	 * 图片区域
	 * @author Ning
	 */
	public class PhotoArea extends LayoutView
	{
		//离开完成
        public static const LEAVE_COMPLETE:String = 'leaveComplete';
		//选择元素
		public static const SELECT_ITEM:String = 'selectItem';
		
		private var _config:PhotoAreaVO;
		
		private var _pics:Array;
		
		// 盒子
		private var _box:Sprite;
		

		
		//行间距
		private var _rowSpacing:Number = 1;
		//纵间距
		private var _columnSpacing:Number = 1;
		
		private var _layoutPhotoWidth:Number;
		
		private var _layoutPhotoHeight:Number
		
		private var _photoWidth:Number;
		
		private var _photoHeight:Number;
		
		//当前的最后一行序号
		private var _lastRow:int;
		//列数
		private var _column:int;
		//行数
		private var _row:int;
		
		//子元素集合
		private var _items:Array = [];
		
		private var _lock:Boolean;
		public function set lock(lock:Boolean):void
		{
			_lock = lock;
			if (lock){
				AppGlobal.STAGE.removeEventListener(MouseEvent.MOUSE_MOVE, onMove);
			    AppGlobal.STAGE.removeEventListener(MouseEvent.MOUSE_WHEEL, onWheel);
			}
			else {
				AppGlobal.STAGE.addEventListener(MouseEvent.MOUSE_MOVE, onMove);
			    AppGlobal.STAGE.addEventListener(MouseEvent.MOUSE_WHEEL, onWheel);
			}
		}
		public function get lock():Boolean {
			return _lock;
		}
		
		public function PhotoArea() 
		{
			init();
		}
		private function init():void
		{
			_box = new Sprite();
			addChild(_box);
			this.lock = false;
		}
		public function updateConfig(config:PhotoAreaVO):void
		{
			_config = config;
			_layoutPhotoWidth = _config.layoutPhotoWidth;
			_layoutPhotoHeight = _config.layoutPhotoHeight;
		}
		public function updateData(data:Array):void
		{
			_pics = data;
			if (_box.numChildren != 0) {
				addEventListener(PhotoArea.LEAVE_COMPLETE, onComplete);
				leave();
			}
			else 
			    onComplete();
				
			function onComplete(evt:Event=null):void
			{
				removeEventListener(PhotoArea.LEAVE_COMPLETE, onComplete);
				
				//清空子元素集合
				while (_items.length > 0) {
					var item:PhotoItem = _items[0] as PhotoItem;
					if (item) {
						item.clear();
						item.removeEventListener(MouseEvent.CLICK, onItemClick);
						if (_box.contains(item))
							_box.removeChild(item);
						_items.splice(0, 1);
						ObjectPool.getPool(PhotoItem).returnObject(item);
					}
				}
				
				//创建item
				for (var i:int = 0; i < _pics.length; i++ )
				{
					var obj:PhotoVO = _pics[i];
					item = ObjectPool.getPool(PhotoItem).borrowObject() as PhotoItem;
					item.updateConfig(_config.photoWidth, _config.photoHeight, _layoutPhotoWidth, _layoutPhotoHeight);
					item.updateData(obj);
					item.addEventListener(MouseEvent.CLICK, onItemClick);
					_items[i] = item;
				}
				
				layout();
			}
		}
		//更新区域布局
		public function updateAreaLayout():void 
		{
			_column = Math.ceil( AppGlobal.STAGE.stageWidth / _layoutPhotoWidth);
			_row = (AppGlobal.STAGE.stageHeight - _config.layoutVO.top - _config.layoutVO.bottom) / _layoutPhotoHeight;
			
			for (var i:int = 0; i < _row * _column; i++ )
			{
				var item:PhotoItem = getItemAt(i);
				if (!item)
				    continue;
				var x:Number = i % _column * (_layoutPhotoWidth + _columnSpacing);
				var y:Number = int(i / _column) * (_layoutPhotoHeight + _rowSpacing);
				item.x = x;
				item.y = -this.y - _layoutPhotoHeight;
				Tweener.addTween(item, { time:.5,delay:Math.random() * .2,y:y,onComplete:onComplete} );
				_box.addChild(item);
			}

			_lastRow = _row;
			//布局完成后，滚轮有效
			_wheelFlag = true;
			function onComplete():void
			{
				PhotoItem(this).load();
			}
			
		}
		override public function layout():void 
		{
			
			if(_config)
			    this.y = _config.layoutVO.top;
				
			if (_box.numChildren == 0) {
				updateAreaLayout();  
			}
			else {
				addEventListener(PhotoArea.LEAVE_COMPLETE,onLeaveComplete)
				leave();
			}   
		}
		private function onLeaveComplete(evt:Event):void
		{
			removeEventListener(PhotoArea.LEAVE_COMPLETE, onLeaveComplete);
			updateAreaLayout();
		}
		//内容离开，所有缓动完成后重新布局
		public function leave():void
		{
			//离开时，滚轮无效
			_wheelFlag = false;
			//如果没有子元素，则布局
			for (var i:int = 0; i < _box.numChildren; i++ )
			{
				var item:PhotoItem = _box.getChildAt(i) as PhotoItem;
				if (item) {
					//先停止所有元素的缓动
					Tweener.removeTweens(item);
				    Tweener.addTween(item, { time:1.2,delay:Math.random()*.3, y:AppGlobal.STAGE.stageHeight,onComplete:onComplete } );
				}
			}
			function onComplete():void
			{
				if (_box.contains(this))
				    _box.removeChild(this)
				if (_box.numChildren == 0)
				    dispatchEvent(new Event(LEAVE_COMPLETE));
			}
		}
		
		private function onMove(evt:MouseEvent=null):void
		{
			//宽度发生变化，列数要重算，
			var w:Number = Math.ceil( AppGlobal.STAGE.stageWidth / _layoutPhotoWidth) * (_layoutPhotoWidth + _columnSpacing)
			var x:Number = (AppGlobal.STAGE.stageWidth - w) / (AppGlobal.STAGE.stageWidth / AppGlobal.STAGE.mouseX);
			Tweener.addTween(this, { time:1, x: x } );
		}
		private function next():void
		{
			//最后一行时返回
			if (_lastRow * _column >= _pics.length )
			    return;
				
			//其它行上移
			for (var i:int = 0; i < _column * (_row - 1); i++)
			{
				var item:PhotoItem = getItemAt((_lastRow - _row + 1) * _column + i);
				if (item) {
					Tweener.removeTweens(item);
				    Tweener.addTween(item, { time:.5, delay:Math.random() * .3, y:int((_column+i) / _column-1)*(_layoutPhotoHeight+_rowSpacing)} );
				}
			}
			//最后一行拉上
			for (i = 0; i < _column; i++ )
			{
				item = getItemAt(_lastRow * _column + i);
				if (!item)
				    break;
				var x:Number = i % _column * (_layoutPhotoWidth + _columnSpacing);
				var y:Number = (_row - 1) * (_layoutPhotoHeight + _rowSpacing);
				_box.addChild(item);
				item.y = AppGlobal.STAGE.stageHeight;
				item.x = x;
				setTimeout(item.load, 1500);
				Tweener.addTween(item, { time:1.2, delay:Math.random() * .3, y:y} );
			}
			
			//第一行飞上离开
			for (i=0; i < _column; i++ )
		    {
				item = getItemAt((_lastRow - _row ) * _column + i);
				if (item) {
					Tweener.removeTweens(item);
				    Tweener.addTween(item, { time:.3, delay:Math.random() * .2, y: -_layoutPhotoHeight-this.y, onComplete:onComplete,transition:'easeInQuad' } );
				}
			}
			
			_lastRow += 1;
			
			
			function onComplete():void
			{
				if (_box.contains(this))
				_box.removeChild(this)
			}
		}
		private function prev():void
		{
			//到第一行时返回
			if (_lastRow==_row)
			    return;
				
			//其它行下移
			for (var i:int = 0; i < _column * (_row - 1); i++)
			{
				var item:PhotoItem = getItemAt((_lastRow - _row) * _column + i);
				if (item) {
					Tweener.removeTweens(item);
				    Tweener.addTween(item, { time:.5, delay:Math.random() * .3, y:(int(i/ _column)+1)*(_layoutPhotoHeight+_rowSpacing)} );
				}
			}
			//第一行进入
			for (i=0; i < _column; i++ )
		    {
				item = getItemAt((_lastRow -_row - 1) * _column + i);
				item.y = -_layoutPhotoHeight - this.y;
				item.x = i % _column * (_layoutPhotoWidth + _columnSpacing);
				_box.addChild(item);
				Tweener.addTween(item, { time:.3, delay:Math.random() * .2, y:0,transition:'easeInQuad' } );
			}
			//最后一行离开
			for (i = 0; i < _column; i++ )
			{
				item = getItemAt((_lastRow - 1) * _column + i);
				if (item) {
					Tweener.removeTweens(item);
				    Tweener.addTween(item, { time:.3, delay:Math.random() * .2, y: AppGlobal.STAGE.stageHeight, onComplete:onComplete,transition:'easeInQuad' } );
				}
			}
			
			_lastRow -= 1;
			
			function onComplete():void
			{
				if (_box.contains(this))
				    _box.removeChild(this);
			}
			
		}
		private function clear():void
		{
			
		}

		//滚轮控制标记 使用一次滚轮后.5秒后才能使用下一次
		private var _wheelFlag:Boolean = true;
		private function onWheel(evt:MouseEvent):void
		{
			if (_wheelFlag) {
				if (evt.delta < 0) {
					next();

				}
			    else {
					prev();
				}
				_wheelFlag = false;
				setTimeout(resetWheelFlag, 500);
			}
		}
		private function resetWheelFlag():void
		{
			_wheelFlag = true;
		}
		private function getItemAt(index:int):PhotoItem {
			return _items[index] as PhotoItem;
		}
		
		private function onItemClick(evt:MouseEvent):void
		{
			var item:PhotoItem = evt.currentTarget as PhotoItem;
			var index:int = _items.indexOf(item);
			dispatchEvent(new DataEvent(SELECT_ITEM, index));
		}
	}
}
import application.model.VO.PhotoVO;
import flash.display.Bitmap;
import flash.display.Loader;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import caurina.transitions.Tweener;
import flash.net.URLRequest;
import flash.utils.setTimeout;
import ginger.utils.DisplayUtil;
class PhotoItem extends Sprite
{
	private var _photoWidth:Number;
	private var _photoHeight:Number;
	private var _layoutPhotoWidth:Number;
	private var _layoutPhotoHeight:Number;
	
	private var _mask:Shape;
	private var _content:Sprite;
	private var _loader:Loader;
	private var _bitmap:Bitmap;
	
	private var _data:PhotoVO;
	
	private var _loadFlag:Boolean;
	
	public function PhotoItem():void
	{
		init();
	}
	public function updateConfig(photoWidth:Number, photoHeight:Number, layoutPhotoWidth:Number, layoutPhotoHeight:Number):void {
		_photoWidth = photoWidth;
		_photoHeight = photoHeight;
		_layoutPhotoWidth = layoutPhotoWidth;
		_layoutPhotoHeight = layoutPhotoHeight;
		
		updateUI();
		updateLayout();
	}
	private function updateUI():void
	{
		_content.graphics.clear();
		_content.graphics.beginFill(0xcccccc);
		_content.graphics.drawRect(0, 0, _photoWidth, _photoHeight);
		_content.graphics.endFill();
		
		_mask.graphics.clear();
		_mask.graphics.beginFill(0);
		_mask.graphics.drawRect(0, 0, _layoutPhotoWidth,  _layoutPhotoHeight);
		_mask.graphics.endFill();
	}
	private function updateLayout():void
	{
		//内容容器的x,y坐标为负，中间位置可视

		_content.x = (_layoutPhotoWidth - _photoWidth) / 2;
		_content.y = (_layoutPhotoHeight - _photoHeight) / 2;
	}
	private function init():void
	{
		_content = new Sprite();
		addChild(_content);
		
		_loader = new Loader();
		_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
		
		
		_mask = new Shape();
		addChild(_mask);
		_content.mask = _mask;
		
		this.buttonMode = true;
		
		addEventListener(MouseEvent.ROLL_OVER, onOver);
		addEventListener(MouseEvent.ROLL_OUT, onOut);
	}
	public function updateData(data:PhotoVO):void {
		_data = data;
	}
	public function load():void
	{
		if(!_loadFlag)
		    _loader.load(new URLRequest(_data.url1));
	}
	public function clear():void
	{
		if (_bitmap) {
			if (_content.contains(_bitmap))
			    _content.removeChild(_bitmap);
		    _bitmap.bitmapData.dispose();
		}
		_loadFlag = false;
	}
	private function onComplete(evt:Event):void
	{
		_loadFlag = true;
		_bitmap = evt.target.content as Bitmap;
		_content.addChild(_bitmap);
		DisplayUtil.setTheMostSuitableSize(_bitmap, _photoWidth, _photoHeight);
		_bitmap.smoothing = true;
		_bitmap.alpha = 0;
		Tweener.addTween(_bitmap, { time:1, alpha:1,transition:'easeInSine' } );
	}
	private function onOver(evt:MouseEvent):void {
		//移至父容器显示列表的最上端
		parent.swapChildrenAt(parent.getChildIndex(this), parent.numChildren-1);
		//改变遮罩，以达到从中心放大的效果
		Tweener.addTween(_mask, {x:_content.x,y:_content.y,time:1.5,width:_photoWidth,height:_photoHeight } );
	}
	private function onOut(evt:MouseEvent):void {
		Tweener.addTween(_mask, { x:0, y:0, time:1.5, width:_layoutPhotoWidth, height:_layoutPhotoHeight } );
	}
}